package com.cqggrw.service.impl;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import com.cqggrw.dao.BookDaoI;
import com.cqggrw.dao.impl.BookDaoImpl;
import com.cqggrw.domain.Book;
import com.cqggrw.service.BookServiceI;
import com.cqggrw.util.Utils;
import com.cqggrw.util.ZipUtil;

public class BookServiceImpl implements BookServiceI {

	private BookDaoI dao = new BookDaoImpl();
	
	public boolean add(Book book, String realPath) {
		boolean flag = false;
		
		if(book.getImg() != null && book.getFmImg() != null) {
			book.setFmImgFileName(UUID.randomUUID().toString());
			String savePath = realPath + Utils.separator + "images" + Utils.separator + "bookImg" + Utils.separator;
			try {
				Utils.log(savePath);

				if(Utils.upFile(book.getFmImgFileName() + ".jpg", savePath, book.getFmImg())
						&& ZipUtil.unZipFile(book.getImg(), savePath+book.getFmImgFileName())) {
					if(dao.add(book)) {
						flag = true;
					}
				}
			} catch (IOException e) {
				Utils.log(e);
			}
		}
		
		return flag;
	}

	public boolean del(Integer id) {
		return dao.del(id);
	}

	public Book get(Integer id) {
		return dao.get(id);
	}

	public Object get(Book book) {
		List<Book> list = dao.get(book);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("total", dao.getTotal());
		map.put("rows", list);
		return map;
	}
	
	public List<Book> getList(Book book) {
		return dao.get(book);
	}

	public List<String> getBookImgName() {
		// TODO Auto-generated method stub
		return null;
	}

	public Object getBookImgName(String bookImg, String realPath) {
		StringBuffer strList = new StringBuffer();
		String[] list = (new File(realPath +Utils.separator+"images" +Utils.separator +"bookImg"+Utils.separator+bookImg)).list();
		if(list != null && list.length>0) {
			for(int i = 0; i < list.length; i++) {
				if(i != 0) {
					strList.append(",");
				}
				strList.append(list[i]);
			}
		}
		return strList.toString();
	}

	public boolean modify(Book book, String realPath) {
		book.setFmImgFileName(book.getFmImgFileName2());
		String savePath = realPath + Utils.separator + "images" + Utils.separator + "bookImg" + Utils.separator;
		book.setFmImgFileName(book.getFmImgFileName().replace(".", ",").split(",")[0]);
		try {
			if(book.getFmImg() != null){
				Utils.log(book.getFmImgFileName());
				if(!Utils.upFile(book.getFmImgFileName() + ".jpg", savePath, book.getFmImg())) {
					return false;
				}
			}
			if(book.getImg() != null){
				Utils.deleteDir(new File(savePath+book.getFmImgFileName()));
				if(!Utils.unzip(book.getImg(), savePath+book.getFmImgFileName())) {
					return false;
				}
			}
			if(!dao.modify(book)) {
				return false;
			}
		} catch (IOException e1) {
			Utils.log(e1);
		}
		
		return true;
	}

}
